package com.tiger.cloud.controller.rejection;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.tiger.cloud.common.jpush.JpushInterface;
import com.tiger.cloud.common.mapper.JsonMapper;
import com.tiger.cloud.common.mybatis.BaseController;
import com.tiger.cloud.enums.DeleteEnum;
import com.tiger.cloud.filter.CurrentUserId;
import com.tiger.cloud.filter.IgnoreAuth;
import com.tiger.cloud.form.UserCompanyInfoForm;
import com.tiger.cloud.model.crm.Peers;
import com.tiger.cloud.model.crm.UserCompanyInfo;
import com.tiger.cloud.model.rejection.Rejection;
import com.tiger.cloud.model.rejection.UserRejection;
import com.tiger.cloud.service.crm.IPeersService;
import com.tiger.cloud.service.crm.IUserCompanyInfoService;
import com.tiger.cloud.service.rejection.IUserRejectionService;
import com.tiger.cloud.service.rejection.RejectionService;
import com.tiger.cloud.util.ErrorCode;
import com.tiger.cloud.util.Page;
import com.tiger.cloud.util.Response;
import com.tiger.cloud.util.ResponseUtil;
import com.tiger.cloud.util.URLUtils;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 接单/甩单
 */
@Controller
@RequestMapping(value = "rejection")
@Api(value = "接单/甩单", tags = "接单/甩单")
public class RejectionController extends BaseController {

	private static final Logger logger = Logger.getLogger(RejectionController.class);
	
	@Autowired
	private RejectionService rejectionService;
	@Autowired
	private IUserRejectionService userRejectionService;
	@Autowired
	private IPeersService peersService;
	@Autowired
	private IUserCompanyInfoService userCompanyInfoService;
	@Autowired
	private JpushInterface jpushInterface;
	
	@RequestMapping(value = "test", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "交易大厅",notes = "交易大厅")
	public Response test(@CurrentUserId Long userId,String alias){
		Map<String, Object> data=new HashMap<String, Object>();
		Map<String, Object> params=new HashMap<String, Object>();
		
		params.put("id", "90");//l
		params.put("content", "我是内容");
		
		data.put("type", 1);
		data.put("data",JsonMapper.nonDefaultMapper().toJson(params));
		
		List<String> aliasesList=new ArrayList<String>();
		aliasesList.add(alias);
		
		return ResponseUtil.ok(jpushInterface.sendAllClientsPushMessage(aliasesList,"notification", data));
	}
	
	@RequestMapping(value = "tradeFind", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "交易大厅",notes = "交易大厅")
	public Response tradeFind(@CurrentUserId Long userId,@RequestBody Rejection rejection){
//		if(rejection.getResourceProvinceId()==null){
//			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID,"resourceProvinceId必传");
//		}
//		if(rejection.getResourceAreaId()==null){
//			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID,"resourceAreaId必传");
//		}
//		if(rejection.getResourceCityId()==null){
//			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID,"resourceCityId必传");
//		}
		rejection.setOrderBy("CRM_REJECTION.create_time desc");
		rejection.setUserId(userId);
		Page<Rejection> datas=rejectionService.tradeFindFindByEntity(rejection);
		
		UserCompanyInfo userCompanyInfo=new UserCompanyInfo();
		userCompanyInfo.setUserId(userId);
		Map<String, Object> findUserCompanyInfo=rejectionService.getByUserId(userId);
		
		if(findUserCompanyInfo!=null){
			datas.setDefaultValues(findUserCompanyInfo.get("biz_type"));
		}
		return ResponseUtil.ok(datas);
	}

	@RequestMapping(value = "get", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "获取单条甩单/接单信息",notes = "获取单条甩单/接单信息")
	public Response get(@CurrentUserId Long userId,@RequestBody Rejection rejection){
		logger.debug("RejectionController get request[rejection]:"+rejection);
		if(rejection.getId()==null){
			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID,"id必传");
		}
		UserRejection userRejection = new UserRejection();
		userRejection.setUserId(userId);
		userRejection.setRejectionId(rejection.getId());
		if(userRejectionService.countByEntity(userRejection) == 0 ){
			userRejectionService.insertRejection(userRejection);
		}
		Rejection data = rejectionService.get(rejection.getId());
		if(data != null){
			Peers peers = new Peers();
			peers.setUserId(userId);
			peers.setPeerId(data.getUserId());
			if(peersService.countByUserId(peers)>0){
				//是否同行
				data.setHasPeer(true);
			}else{
				data.setHasPeer(false);
			};
		}
		logger.debug("RejectionController get response[data]:"+data);
		return ResponseUtil.ok(data);
	}
	
	@IgnoreAuth
	@CrossOrigin
	@RequestMapping(value = "findRejection", method = RequestMethod.POST)
	@ResponseBody 
	@ApiOperation(value = "我的甩单列表",notes = "我的甩单列表")
	public Response findRejection(@CurrentUserId Long userId,@RequestBody Rejection rejection){
		logger.debug("RejectionController findRejection request[rejection]:"+rejection);
		rejection.setUserId(userId);
		rejection.setOrderBy("CRM_REJECTION.create_time desc");
		Page<Rejection> datas = rejectionService.page1(rejection);
		logger.debug("RejectionController findRejection response[datas]:"+datas);
		return ResponseUtil.ok(datas);
	}
	
	@RequestMapping(value = "myRejectionCount", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "我的接单列表个数",notes = "我的接单列表")
	public Response myRejectionCount(@CurrentUserId Long userId,@RequestBody Rejection rejection){
		rejection.setUserId(userId);
		
		UserCompanyInfo userCompanyInfo = new UserCompanyInfo();
		userCompanyInfo.setUserId(userId);
		UserCompanyInfo findUserCompanyInfo=userCompanyInfoService.findOne(userCompanyInfo);
		
		if(findUserCompanyInfo != null){
//			rejection.setResourceAreaId(findUserCompanyInfo.getDistrictId());
			rejection.setResourceCityId(findUserCompanyInfo.getCityId());
			rejection.setResourceProvinceId(findUserCompanyInfo.getProvinceId());
		}
		
		Long datas=rejectionService.myRejectionCountByEntity(rejection);
		return ResponseUtil.ok(datas);
	}
	
	
	/**
	 * 我的接单列表
	 * <p>Title: RejectionController.java</p>
	 * @author huxusheng  
	 * @date 2018年5月28日  
	 * @param userId
	 * @param rejection
	 * @return
	 */
	@RequestMapping(value = "pullRejection", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "我的接单列表",notes = "我的接单列表")
	public Response pullRejection(@CurrentUserId Long userId,@RequestBody Rejection rejection){
		rejection.setUserId(userId);
		rejection.setOrderBy("CRM_REJECTION.create_time desc");

		UserCompanyInfo userCompanyInfo=new UserCompanyInfo();
		userCompanyInfo.setUserId(userId);
		UserCompanyInfo findUserCompanyInfo=userCompanyInfoService.findOne(userCompanyInfo);
		
		if(findUserCompanyInfo!=null){
//			rejection.setResourceAreaId(findUserCompanyInfo.getDistrictId());
			rejection.setResourceCityId(findUserCompanyInfo.getCityId());
			rejection.setResourceProvinceId(findUserCompanyInfo.getProvinceId());
		}
		
		
		//省份id,城市id,用户userid
		Page<Rejection> datas=rejectionService.pullRejection(rejection);
		return ResponseUtil.ok(datas);
	}
	
	/**
	 * 我的接单列表By企业
	 * 加上定向甩单到企业用户的单
	 * <p>Title: RejectionController.java</p>
	 * @author huxusheng  
	 * @date 2018年5月28日  
	 * @param userId
	 * @param rejection
	 * @return
	 */
	@RequestMapping(value = "pullRejection1", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "我的接单列表(企业)",notes = "我的接单列表(企业)")
	public Response pullRejection1(@CurrentUserId Long userId,@RequestBody Rejection rejection){
		rejection.setUserId(userId);
		rejection.setOrderBy("CRM_REJECTION.create_time desc");

		UserCompanyInfo userCompanyInfo=new UserCompanyInfo();
		userCompanyInfo.setUserId(userId);
		UserCompanyInfo findUserCompanyInfo=userCompanyInfoService.findOne(userCompanyInfo);
		
		if(findUserCompanyInfo!=null){
//			rejection.setResourceAreaId(findUserCompanyInfo.getDistrictId());
			rejection.setResourceCityId(findUserCompanyInfo.getCityId());
			rejection.setResourceProvinceId(findUserCompanyInfo.getProvinceId());
		}
		
		
		//省份id,城市id,用户userid
		Page<Rejection> datas=rejectionService.pullRejection(rejection);
		return ResponseUtil.ok(datas);
	}
	
	
	
	@RequestMapping(value = "find", method = RequestMethod.POST)
	@ResponseBody
	public Response find(@CurrentUserId Long userId,@RequestBody Rejection rejection){
		Page<Rejection> datas=rejectionService.page(rejection);
		return ResponseUtil.ok(datas);
	}
	
	@RequestMapping(value = "list", method = RequestMethod.POST)
	@ResponseBody
	public Response list(@CurrentUserId Long userId,@RequestBody Rejection rejection){
		return ResponseUtil.ok(rejectionService.find(rejection));
	}
	
	@RequestMapping(value = "updateStatus", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "更单条甩单/接单信息",notes = "获取单条甩单/接单信息")
	public Response updateStatus(@CurrentUserId Long userId,HttpServletRequest request,@RequestBody  Rejection rejection){
		rejectionService.update(rejection);
		return ResponseUtil.ok();
	}
	
	@RequestMapping(value = "remove", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "删除甩单/接单信息",notes = "删除甩单/接单信息")
	public Response remove(@CurrentUserId Long userId,HttpServletRequest request,@RequestBody  Rejection rejection){
		rejectionService.remove(rejection);
		return ResponseUtil.ok();
	}
	
	
	/**
	 * 甩单给个人或企业
	 * <p>Title: RejectionController.java</p>
	 * @author huxusheng  
	 * @date 2018年5月28日  
	 * @param userId
	 * @param request
	 * @param rejection
	 * @return
	 */
	@RequestMapping(value = "add", method = RequestMethod.POST)
	@ResponseBody
	public Response add(@CurrentUserId Long userId,HttpServletRequest request,@RequestBody Rejection rejection){
		logger.debug("RejectionController add request[rejection]:"+rejection);
		Response result = new Response();
		rejection.setUserId(userId);
		if( rejection.getExtParams() != null ){
			rejection.setExtParams(URLUtils.decodeURL(StringEscapeUtils.escapeHtml4(rejection.getExtParams())));
		}
		try {
			boolean bool = rejectionService.insert(rejection);
			logger.debug("RejectionController rejectionService.insert response[bool]:"+bool);
			if (!bool) {
				result = ResponseUtil.error();
			}
			rejection.setUserId(userId);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
		/*List<String> clientList = rejectionService.findRejectionClients(rejection);
		Map<String, Object> data=new HashMap<String, Object>();
		Map<String, Object> params=new HashMap<String, Object>();
		params.put("id", rejection.getId());
		String typeText="";
		if(rejection.getLoanType().equals("0")){
			typeText="车辆抵押";
		}else if(rejection.getLoanType().equals("1")){
			typeText="无抵押";
		}else if(rejection.getLoanType().equals("2")){
			typeText="零用贷";
		}else if(rejection.getLoanType().equals("3")){
			typeText="垫资";
		}else if(rejection.getLoanType().equals("4")){
			typeText="不动产抵押";
		}else if(rejection.getLoanType().equals("5")){
			typeText="其他抵押";
		}else if(rejection.getLoanType().equals("6")){
			typeText="银行中介";
		}else if(rejection.getLoanType().equals("7")){
			typeText="资方";
		}else if(rejection.getLoanType().equals("8")){
			typeText="金融律师";
		}else if(rejection.getLoanType().equals("9")){
			typeText="征信查询";
		}else if(rejection.getLoanType().equals("10")){
			typeText="催收";
		}else if(rejection.getLoanType().equals("11")){
			typeText="资产处理";
		}else if(rejection.getLoanType().equals("12")){
			typeText="其他金服";
		}else if(rejection.getLoanType().equals("13")){
			typeText="房产经纪人";
		}else if(rejection.getLoanType().equals("14")){
			typeText="车辆经纪人";
		}else if(rejection.getLoanType().equals("15")){
			typeText="保险经纪人";
		}
		try {
			
			String msString="系统为您匹配到1个甩单业务\""+typeText+","+rejection.getAmount()+"万,"+rejection.getLoanTerm()+"个月\",请立即到\"接单\"列表中查看信息并迅速联 络甩单人,以免错失商机。祝您成功！";
			params.put("content",msString);
			data.put("type", "3");
			data.put("data", JsonMapper.nonDefaultMapper().toJson(params));
			jpushInterface.sendAllClientsPushMessage(clientList,"notification", data);
			
			java.util.Date  date=new java.util.Date();
			DataObject dataObject=new DataObject();
			dataObject.setJpushCode(clientList);
			dataObject.setMsg(msString);
			
			date=DateTimeUtil.addMinutes(date, 10);
			String cron=date.getSeconds()+ " "+date.getMinutes()+" "+date.getHours()+" "+date.getMonth()+" ? "+date.getYear();
			SysScheduleJob scheduleJob1= new SysScheduleJob();
			scheduleJob1.setCronExpression(cron);
			scheduleJob1.setJobGroup("com.tiger.cloud.service.system.TaskExcutor");
			scheduleJob1.setJobName("TaskExcutor.pushMsg.01."+rejection.getId());
			scheduleJob1.setTempId(JsonMapper.nonDefaultMapper().toJson(dataObject));
			scheduleJob1.setMethodName("pushMsg");
			sysScheduleJobService.addJob(scheduleJob1);
			
			date=DateTimeUtil.addMinutes(date, 10);
			cron=date.getSeconds()+ " "+date.getMinutes()+" "+date.getHours()+" "+date.getMonth()+" ? "+date.getYear();
			SysScheduleJob scheduleJob2= new SysScheduleJob();
			scheduleJob2.setCronExpression(cron);
			scheduleJob2.setJobGroup("com.tiger.cloud.service.system.TaskExcutor");
			scheduleJob1.setJobName("TaskExcutor.pushMsg.02."+rejection.getId());
			scheduleJob1.setTempId(JsonMapper.nonDefaultMapper().toJson(dataObject));
			scheduleJob1.setMethodName("pushMsg");
			sysScheduleJobService.addJob(scheduleJob2);
		} catch (Exception e) {
			e.printStackTrace();
		}*/
		return result;
	}
	
	
	@RequestMapping(value = {"delete"},method = {RequestMethod.POST})
    @ResponseBody
    public Response delete(@CurrentUserId Long userId, @RequestBody Rejection rejection) {
        this.rejectionService.removeRejection(rejection);
        return ResponseUtil.ok();
    }
	
	
	/**
	 * 查询可以甩单给企业的  企业列表
	 * 限制条件：地区区域相同，类型相同
	 * <p>Title: RejectionController.java</p>
	 * @author huxusheng  
	 * @date 2018年5月24日  
	 * @param userCompanyInfo
	 * @return
	 */
	@IgnoreAuth
	@CrossOrigin
	@RequestMapping(value = "/findFlingEnterprise", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "查询可以甩单给企业的  企业列表",notes = "查询可以甩单给企业的  企业列表")
	public Response findFlingEnterprise(@RequestBody UserCompanyInfo userCompanyInfo) {
		logger.debug("RejectionController findFlingEnterprise request[userCompanyInfo]:"+userCompanyInfo);
		Response result = new Response();
		if (null == userCompanyInfo.getProvinceId()) {
			result = ResponseUtil.error(ErrorCode.PROVINCE_ID_NULL);
		}
		else if (null == userCompanyInfo.getCityId()) {
			result = ResponseUtil.error(ErrorCode.CITY_ID_NULL);
		}
		else if (null == userCompanyInfo.getBizType()) {
			result = ResponseUtil.error(ErrorCode.BIZ_TYPE_NULL);
		}
		else {
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("isDelete", DeleteEnum.NOMAIL);
			params.put("provinceId", userCompanyInfo.getProvinceId());
			params.put("cityId", userCompanyInfo.getCityId());
			params.put("districtId", userCompanyInfo.getDistrictId());
			params.put("bizType", userCompanyInfo.getBizType());
			params.put("limitStart", userCompanyInfo.getLimitStart());
			params.put("limitEnd", 20);
			//查询符合条件的企业
			List<UserCompanyInfoForm> list = userCompanyInfoService.findFlingEnterprise(params);
			result.setData(list);
		}
		logger.debug("RejectionController findFlingEnterprise response[result]:"+result);
		return result;
	}
	
	
	

}